
package net.swa.system.util.interceptor;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

import net.swa.dewei.web.action.CommonAction;
import net.swa.system.beans.entity.OperationLog;
import net.swa.system.beans.entity.User;
import net.swa.system.service.ICommonService;
import net.swa.system.util.annotation.Log;
import net.swa.system.web.action.AbstractBaseAction;
import net.swa.util.DateUtils;
import net.swa.util.http.HttpServletUtil;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**操作日志拦截器**/
public class LogInterceptor extends AbstractInterceptor
{
    private static final long serialVersionUID = 4025580326719578158L;

    public String intercept(ActionInvocation ai) throws Exception //参数为代理类
    {
        ActionProxy proxy = ai.getProxy();
        Object action = proxy.getAction();
        AbstractBaseAction baseAction = (AbstractBaseAction) action;
        Class<?> clz = action.getClass();
        String methodName = proxy.getMethod();
        Method method = clz.getMethod(methodName);
        if (method.isAnnotationPresent(Log.class))
        {
            Log log = method.getAnnotation(Log.class);
            String descript = log.description();
            Method getCommonService = clz.getMethod("getCommonService");
            ICommonService commonService = (ICommonService) getCommonService.invoke(action);
            OperationLog oLog = new OperationLog();
            User user = baseAction.getCurrentUser();
            if (user == null)
            {
                return "login";
            }
            oLog.setUserid(user.getUserid());
            oLog.setUpdateDate(DateUtils.getCurrDate(null));

            //            			String uri=proxy.getNamespace()+"/"+methodName;
            HttpServletRequest request = ServletActionContext.getRequest();
            String ip = HttpServletUtil.getIpFromRequest(request);
            oLog.setIp(ip);
            StringBuilder uri = new StringBuilder();
            uri.append(proxy.getNamespace());
            uri.append("/");
            uri.append(methodName);
            if (CommonAction.class.equals(clz))
            {
                uri.append(".do?");
                //				Map<String, Object> params=ai.getInvocationContext().getParameters();
                //				Set<String> keys=params.keySet();
                //				for(String key:keys){
                //					String[] values=(String[])params.get(key);
                //					for(String value:values){
                //						uri.append(key+"="+value.toString()+"&");
                //					}
                //				}
            }
            oLog.setUri(uri.toString());
            oLog.setDescript(descript);
            commonService.commonAdd(oLog);
        }
        return ai.invoke();
    }

}
